#coding=utf-8
#LightCam 查询mongodb
#init by hfh 20150521

import socket,os,time,re
import lc_libs
import multiprocessing,subprocess,traceback
import sys,pymongo,json

length = len(sys.argv)
if length<5:
	strs="wrong para,please input remoteip remoteport dbname tablename expr\n just like: \n LightCamPy lc_remotequery.py 127.0.0.1 1960 lc_alert lc_status /tmp/query.json"
	#strs="wrong para,please input dbname tablename expr \n just like: \n LightCamPy lc_query.py lc_alert lc_status {\\\"_id\\\":{\\\"\$ne\\\":0}}"
	print strs
	exit(0)

remoteip=sys.argv[1]
remoteport=sys.argv[2]
dbname=sys.argv[3]
tablename=sys.argv[4]
jsonfile=sys.argv[5]

lchome=lc_libs.lc_getlchome()

comd="LightCamPy %s/scripts/lc_manager.py %s %s comd \"echo \\$LIGHTCAM_HOME\"" % (lchome,remoteip,remoteport)
popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
while True:
	if popen.poll()==None:
		time.sleep(0.1)
		continue
	else:
		break
remotelchome=popen.stdout.read().strip('\r\n')

comd="LightCamPy %s/scripts/lc_manager.py %s %s put \"%s %s/scripts/lc_query.json\"" % (lchome,remoteip,remoteport,jsonfile,remotelchome)
popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
while True:
	if popen.poll()==None:
		time.sleep(0.1)
		continue
	else:
		break

comd="LightCamPy %s/scripts/lc_manager.py %s %s comd \"LightCamPy %s/scripts/lc_query.py %s %s \"" % (lchome,remoteip,remoteport,remotelchome,dbname,tablename)
popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
while True:
	if popen.poll()==None:
		time.sleep(0.1)
		continue
	else:
		break

querydata=popen.stdout.read().strip('\r\n')
print json.loads(querydata)
